package org.common.utils.tool.window;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

/**
 * text 灰色占位符工具
 * @author zhouzhibing
 * @date 2025/1/7
 */
public class PlaceholderTool {

    /**
     * 注册指定text组件的，灰色占位符。
     * @param textComponent text组件
     * @param hintText 提示文本
     */
    public static void register(JTextComponent textComponent, String hintText) {
        if(textComponent == null) {
            throw new RuntimeException("textComponent is null , hintText = " + hintText);
        }

        //默认显示提示
        PlaceholderTool.focusLost(textComponent, hintText);

        //添加焦点事件提示
        textComponent.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                PlaceholderTool.focusGained(textComponent, hintText);
            }
            @Override
            public void focusLost(FocusEvent e) {
                PlaceholderTool.focusLost(textComponent, hintText);
            }
        });
    }

    /**
     * 获取焦点时显示该提示内容
     * @param textComponent text组件对象
     * @param hintText 提示文本
     */
     private static void focusGained(JTextComponent textComponent, String hintText) {
        //获取焦点时，清空提示内容
        String temp = textComponent.getText();
        if(temp.equals(hintText)) {
            textComponent.setText("");
            textComponent.setForeground(Color.BLACK);
        }
    }


    /**
     * 丢失焦点时显示该提示内容
     * @param textComponent text组件对象
     * @param hintText 提示文本
     */
    private static void focusLost(JTextComponent textComponent, String hintText) {
        //失去焦点时，没有输入内容，显示提示内容
        String temp = textComponent.getText();
        if(temp.isEmpty()) {
            textComponent.setForeground(Color.GRAY);
            textComponent.setText(hintText);
        }
    }

}